package cn.tedu.coolshark.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${imagesPath}")
    public String dirPath;

    @RequestMapping("/upload")
    public String upload(MultipartFile picFile) throws IOException {
        //文件名转换
        String fileName = picFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;
        //日期目录
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        //日期目录的判断与创建
        System.out.println("-----------------"+dirPath);
        File dirFile = new File(dirPath+datePath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        //文件写出
        picFile.transferTo(new File(dirPath+datePath+fileName));
        return datePath+fileName;
    }

    @RequestMapping("/remove")
    public void remove(String url){
        new File(dirPath+url).delete();
    }

}
